<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Pages.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_Model_DbTable_Pages extends Engine_Db_Table implements Engine_Content_Storage_Interface {
	protected $_rowClass = 'Page_Model_Page';
	
	public function loadMetaData(Engine_Content $contentAdapter, $name) {
		$select = $this->select ()->where ( 'url = ?', $name )->orWhere ( 'page_id = ?', $name );
		$page = $this->fetchRow ( $select );
		
		if (! is_object ( $page )) {
			// throw?
			return null;
		}
		
		return $page->toArray ();
	}
	
	public function lastInsertId() {
		$db = $this->getAdapter ();
		$prefix = $this->getTablePrefix ();
		$status = $db->query ( "SHOW TABLE STATUS LIKE '" . $prefix . "page_pages'" )->fetch ();
		
		return ( int ) $status ['Auto_increment'];
	}
	
	public function checkUrl($url) {
		$url = strtolower ( trim ( $url ) );
		$url = preg_replace ( '/[^a-z0-9-]/', '-', $url );
		$url = preg_replace ( '/-+/', "-", $url );
		
		$select = $this->select ();
		$select->where ( 'url = ?', $url );
		$page = $this->fetchRow ( $select );
		
		return isset ( $page->page_id );
	}
	
	public function getSelect($params = array()) {
		$select = $this->select ();
		$prefix = $this->getTablePrefix ();
		
		$select->setIntegrityCheck ( false )->from ( $prefix . 'page_pages' )->where ( $prefix . "page_pages.name <> 'header' AND " . $prefix . "page_pages.name <> 'footer'" )->joinLeft ( $prefix . "page_fields_values", $prefix . "page_fields_values.item_id = " . $prefix . "page_pages.page_id", array () )->joinLeft ( $prefix . "page_fields_options", $prefix . "page_fields_options.option_id = " . $prefix . "page_fields_values.value", array ('category' => 'label', 'category_id' => 'option_id' ) )->where ( $prefix . "page_fields_values.field_id = 1" )->where ( $prefix . "page_fields_options.field_id = 1" );
		
		if (! empty ( $params ['view'] ) && $params ['view'] == 'map') {
			$select->joinLeft ( $prefix . 'page_markers', $prefix . 'page_markers.page_id = ' . $prefix . 'page_pages.page_id', array ('marker_id', 'longitude', 'latitude' ) );
		}
		
		if (! empty ( $params ['tag_id'] )) {
			$select->joinInner ( $prefix . 'core_tagmaps', $prefix . 'core_tagmaps.resource_id = ' . $prefix . 'page_pages.page_id' )->where ( $prefix . "core_tagmaps.resource_type = 'page'" )->where ( $prefix . "core_tagmaps.tag_id = {$params['tag_id']}" );
		}
		
		if (! empty ( $params ['search'] )) {
			$select->where ( $prefix . "page_pages.search = {$params['search']}" );
		}
		
		if (isset ( $params ['sort'] )) {
			switch ($params ['sort']) {
				case 'newest' :
					$select->order ( $prefix . 'page_pages.modified_date DESC' );
					break;
				case 'popular' :
					$select->order ( $prefix . 'page_pages.view_count DESC' );
					break;
				case 'alphabet' :
					$select->order ( $prefix . 'page_pages.title ASC' );
					break;
				default :
					$select->order ( $prefix . 'page_pages.modified_date DESC' );
					break;
			}
		}
		
		if (! empty ( $params ['where'] )) {
			$select->where ( $params ['where'] );
		}
		
		if (! empty ( $params ['city'] )) {
			$select->where ( $prefix . "page_pages.city = '{$params['city']}'" );
		}
		
		if (! empty ( $params ['keyword'] )) {
			$select->where ( $prefix . "page_pages.title LIKE '%{$params['keyword']}%' OR " . $prefix . "page_pages.description LIKE '%{$params['keyword']}%' OR " . $prefix . "page_pages.keywords LIKE '%{$params['keyword']}%'" );
		}
		
		if (! empty ( $params ['fields'] )) {
			$select->joinLeft ( $prefix . 'page_fields_search', $prefix . 'page_fields_search.item_id = ' . $prefix . 'page_pages.page_id', array () );
			$searchParts = Engine_Api::_ ()->fields ()->getSearchQuery ( 'page', $params ['fields'] );
			foreach ( $searchParts as $k => $v ) {
				$select->where ( "`" . $prefix . "page_fields_search`.{$k}", $v );
			}
		}
		
		if (! empty ( $params ['group'] )) {
			$select->group ( $params ['group'] );
		}
		
		if (! empty ( $params ['page_id'] )) {
			$select->where ( $prefix . "page_pages.page_id = {$params['page_id']}" );
		}
		
		if (! empty ( $params ['approved'] )) {
			$select->where ( $prefix . "page_pages.approved = {$params['approved']}" );
		}
		
		if (! empty ( $params ['featured'] )) {
			$select->where ( $prefix . "page_pages.featured = {$params['featured']}" );
		}
		
		return $select;
	}
	
	public function getPaginator($params = array()) {
		$select = $this->getSelect ( $params );
		$paginator = Zend_Paginator::factory ( $select );
		
		if (! empty ( $params ['ipp'] )) {
			$params ['ipp'] = ( int ) $params ['ipp'];
			$paginator->setItemCountPerPage ( $params ['ipp'] );
		}
		
		if (! empty ( $params ['page'] )) {
			$params ['page'] = ( int ) $params ['page'];
			$paginator->setCurrentPageNumber ( $params ['page'] );
		}
		
		return $paginator;
	}
	
	public function loadContent(Engine_Content $content, $name) {
		if (is_array ( $name )) {
			$name = join ( '_', $name );
		}
		
		if (! is_string ( $name ) && ! is_numeric ( $name )) {
			throw new Exception ( 'not string' );
		}
		
		$select = $this->select ()->where ( 'name = ?', $name )->orWhere ( 'page_id = ?', $name );
		$page = $this->fetchRow ( $select );
		
		if (! is_object ( $page )) {
			// throw?
			return null;
		}
		
		// Get all content
		$contentTable = Engine_Api::_ ()->getDbtable ( 'content', 'page' );
		$select = $contentTable->select ()->where ( 'page_id = ?', $page->page_id )->order ( 'order ASC' );
		
		$content = $contentTable->fetchAll ( $select );
		
		// Create structure
		$structure = $this->prepareContentArea ( $content );
		
		// Create element (with structure)
		$element = new Engine_Content_Element_Container ( array ('class' => 'layout_page_' . $page->name, 'elements' => $structure ) );
		
		return $element;
	}
	
	public function prepareContentArea($content, $current = null) {
		$parent_content_id = 0;
		if (null !== $current) {
			$parent_content_id = $current->content_id;
		}
		
		$struct = array ();
		foreach ( $content->getRowsMatching ( 'parent_content_id', $parent_content_id ) as $child ) {
			$elStruct = $this->createElementParams ( $child );
			$elStruct ['elements'] = $this->prepareContentArea ( $content, $child );
			$struct [] = $elStruct;
		}
		
		return $struct;
	}
	
	public function createElementParams($row) {
		$data = array ('identity' => $row->content_id, 'type' => $row->type, 'name' => $row->name, 'order' => $row->order );
		$params = ( array ) $row->params;
		if (isset ( $params ['title'] ))
			$data ['title'] = $params ['title'];
		$data ['params'] = $params;
		
		return $data;
	}
	
	public function deletePage(Page_Model_Page $page) {
		$page->delete ();
		return $this;
	}
	
	public function deletePages($page_ids) {
		if (empty ( $page_ids )) {
			return $this;
		}
		
		foreach ( $page_ids as $page_id ) {
			Engine_Api::_ ()->getItem ( 'page', $page_id )->delete ();
		}
		
		return $this;
	}
}